package org.hughie.log;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author hughie.cheng
 * @since 2025/4/2
 */
public class Logger {
    private ExecutorService executor = Executors.newFixedThreadPool(16);
    private static final String LOG_FILE_PATH = "./data-sync-tool.log";
    private Class<?> clazz;

    public Logger(Class<?> clazz) {
        this.clazz = clazz;
    }

    public void info(String message) {
        String logStr = logTemplate("INFO", message);
        asyncLogWrite(logStr);
    }

    public void info(String message, Object... args) {
        message = replacePlaceholders(message, args);
        String logStr = logTemplate("INFO", message);
        asyncLogWrite(logStr);
    }

    public void warn(String message) {
        String logStr = logTemplate("WARN", message);
        asyncLogWrite(logStr);
    }

    public void error(String message) {
        String logStr = logTemplate("ERROR", message);
        asyncLogWrite(logStr);
    }

    private String replacePlaceholders(String message, Object... args) {
        for (Object arg : args) {
            message = message.replaceFirst("\\{}", String.valueOf(arg));
        }
        return message;
    }

    private String logTemplate(String level, String message) {
        return "[" + level + "]" + LocalDateTime.now() + "[" + Thread.currentThread().getName() + "]" + this.clazz.getName() + " " + message;
    }

    void asyncLogWrite(String logStr) {
        executor.execute(() -> {
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(LOG_FILE_PATH, true))) {
                writer.write(logStr);
                writer.newLine();
            } catch (IOException e) {
                System.err.println("写入文件时发生错误: " + e.getMessage());
                e.printStackTrace();
            }
        });
        System.out.println(logStr);
    }
}
